<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    width="60%"
    placement="right"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :closable="true"
    @close="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="0">
          <a-col :lg="11">
            <a-form-model-item
              label="设备编号"
              :rules="[{ required: true, message: '请输入设备编号!' }]"
            >
              <a-input
                :disabled="editable||showable"
                v-model="model.materialsCode"/>
            </a-form-model-item>
          </a-col>
          <a-col :lg="11">
            <a-form-model-item
              label="设备名称"
              :rules="[{ required: true, message: '请输入设备名称!' }]"
            >
              <a-input
                :disabled="showable"
                v-model="model.materialsName"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :lg="11">
            <a-form-model-item
              label="所属类别"
              :rules="[{ required: true, message: '请输入所属类别code!' }]"
            >
              <a-select
                :disabled="showable"
                :options="category"
                @change="changeCategory"
                v-model="model.category"/>
            </a-form-model-item>
          </a-col>
          <a-col :lg="11">
            <a-form-model-item
              label="供应商"
              :rules="[{ required: false, message: '请输入对应供应商code!' }]"
            >
              <a-select
                mode="multiple"
                :disabled="showable"
                :options="supplierCode"
                v-model="model.supplierCode"
                />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :lg="11">
            <a-form-model-item
              label="计量单位"
              :rules="[{ required: true, message: '请输入计量单位!' }]"
            >
              <a-select
                :disabled="editable||showable"
                @change="changeUnit"
                :options="units"
                v-model="model.unit" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="11">
            <a-form-model-item
              label="规格型号"
              :rules="[{ required: true, message: '请输入规格型号!' }]"
            >
              <a-input
                :disabled="showable"
                v-model="model.num"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :lg="11">
            <a-form-model-item
              label="成本单价"
              :rules="[{ required: true, message: '请输入成本单价!' }]"
            >
              <a-input-number
                style="width: 100%"
                :min="0"
                :disabled="showable"
                v-model="model.unitCost"/>
            </a-form-model-item>
          </a-col>
          <a-col :lg="11">
            <a-form-model-item
              label="最小安全库存"
              :rules="[{ message: '请输入最小安全库存!' }]"
            >
              <a-input-number
                style="width: 100%"
                :min="0"
                :disabled="showable"
                v-model="model.minSafeStock"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :lg="11">
            <a-form-model-item
              label="最大安全库存"
              :rules="[{ message: '请输入最大安全库存!' }]"
            >
              <a-input-number
                style="width: 100%"
                :min="0"
                :disabled="showable"
                v-model="model.maxSafeStock"/>
            </a-form-model-item>
          </a-col>
          <a-col :lg="11"/>
        </a-row>

        <a-divider orientation="left">
          价格表
        </a-divider>
        <j-editable-table
          ref="editableTable"
          :loading="priceTableLoading"
          :columns="priceTableColumns"
          :disabled="showable"
          :dataSource="loadPrice"
          :maxHeight="500"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
        >
        </j-editable-table>

        <a-divider style="margin-top: 60px" />
        <!-- end --材料明细表格 -- end -->

        <!-- start -- 赔偿标准表格 -- start -->
        <a-divider orientation="left">
          单位换算表
        </a-divider>

        <j-editable-table
          ref="unitTable"
          :loading="unitTableLoading"
          :columns="unitTableColumns"
          :disabled="showable"
          :dataSource="loadUnit"
          :maxHeight="500"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          :actionButtonAction="['delete']"
        >
          <template v-slot:buttonBefore>
            <a-button v-if="model.unit" @click="addValues" type="primary" icon="plus" :disabled="showable">
              <template #icon><plus-outlined/></template>
              新增
            </a-button>
          </template>
          <template v-slot:rule >
            <span style="font-size:24px">=</span>
          </template>
        </j-editable-table>
        <a-divider style="margin-top: 50px" />
        <a-divider orientation="left">
          上传
        </a-divider>
        <a-row class="form-row" :gutter="0">
          <a-col :lg="11">
            <a-upload
              :key="imgKey"
              ref="sbsb"
              name="file"
              :disabled="showable"
              list-type="picture-card"
              :show-upload-list="false"
              :remove="handleFileRemove"
              :beforeUpload="beforeFileUpload"
              :customRequest="uploadFunc"
            >
              <img style="width: 100px;height: 100px" v-if="model.pic" :src="this.path+'/sys/common/static/'+model.pic" alt="avatar" />
              <div v-else>
                <a-icon :type="confirmLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  上传
                </div>
              </div>
            </a-upload>
          </a-col>
          <a-col :lg="11">
            <a-form-model-item label="备注 ">
              <a-textarea :rows="4" :disabled="showable" v-model="model.remarks"/>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-divider style="margin-top: 60px" />
      </a-form-model>
    </a-spin>
    <template>

      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button key="cancel" :style="{ marginRight: '8px' }" @click="handleCancel">
          取消
        </a-button>
        <a-button v-show="editable || addable" key="forward" :loading="confirmLoading" type="primary" @click="saveContract">
          保存
        </a-button>
      </div>
    </template>

  </a-drawer>
</template>

<script>
  import JEditableTable from '@/components/jeecg/JEditableTable'
  import { FormMixin } from '@/mixins/FormMixin'
  import { TableMixin } from '@/mixins/TableMixin'
  import { FormModel } from 'ant-design-vue';
  import { FormTypes, getRefPromise, validateFormModelAndTables } from '@/utils/JEditableTableUtil'
  import { dropDownByCode } from '@/api/sys/sys'
  import {addObj,getObj,putObj,getMaterialsCategory,getSupplierCode} from '@/api/base/materialsBase'
  import { httpAction } from '../../../api/manage'

  export default {
    name: 'MaterialsAddOrUpdate',
    mixins: [FormMixin,TableMixin],
    components: {
      FormModel,
      JEditableTable
    },
    props:{
      defaultCategory:String
    },
    data () {
      //this.cachePriceData = this.loadPrice.map(item => ({ ...item }));
      return {
        /**上传图片有关参数
         *
         **/
        imgKey: '',
        confirmLoading: false,
        path: process.env.VUE_APP_API_BASE_URL,
        uploadUrl: 'sys/common/upload',
        /**上传图片有关参数结束
         **/


        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 - 6 }
        },
        materialsId:"",
        confirmLoading: false,
        priceTableLoading:false,
        unitTableLoading:false,
        category: [],
        supplierCode:[],
        units:[],
        form: this.$form.createForm(this),
        materialsData:{},
        priceCount:0,
        unitCount:0,
        rules: {
          unit: [{ required: true, message: '请填写原单位', trigger: 'blur' },],
          goalUnit: [{ required: true, message: '请填写目标单位', trigger: 'blur' }],
          num: [{ required: true, message: '请填写原数量', trigger: 'blur' }],
          goalNum: [{ required: true, message: '请填写目标数量', trigger: 'blur' }],
          leaseOutPrice: [{ required: true, message: '请填写租出单价', trigger: 'blur' }],
          leaseInPrice: [{ required: true, message: '请填写租入单价', trigger: 'blur' }],
          salePrice: [{ required: true, message: '请填写销售单价', trigger: 'blur' }],
        },
        editingKey: '',
        //cachePriceData:[],
        editingUnitKey: '',
        //cacheUnitData:[],
        model:{},
        //加载价格表数据
        loadPrice:[],
        priceTableColumns :[
          {
            title: '对应计量单位',
            key: 'unit',
            type: FormTypes.select,
            options: [],
            width: '15%'
          },
          {
            title: '租出单价',
            key: 'leaseOutPrice',
            type: FormTypes.inputNumber,
            width: '15%'
          },
          {
            title: '租入单价',
            key: 'leaseInPrice',
            type: FormTypes.inputNumber,
            width: '15%'
          },
          {
            title: '销售单价',
            key: 'salePrice',
            type: FormTypes.inputNumber,
            width: '15%'
          },

        ],
        //加载换算表数据
        loadUnit:[],
        defaultUnit:'',
        unitTableColumns:[
          {
            title: '目标数量',
            key: 'goalNum',
            disabled: true,
            type: FormTypes.inputNumber,
            defaultValue:1,
          },
          {
            title: '目标单位',
            key: 'goalUnit',
            type: FormTypes.select,
            options: []
          },
          {
            title: '',
            key: 'rule',
            type: FormTypes.slot,
            slotName: 'rule',
            width: '2.5%'
          },
          {
            title: '原数量',
            type: FormTypes.inputNumber,
            key: 'num'
          },

          {
            title: '原单位',
            key: 'unit',
            disabled: true,
            type: FormTypes.select,
            options: []
          },

        ],
        list:[]
      }
    },
    methods: {
      //多选
      // handleChange = (value: String[]) => {
      //   console.log(`selected ${value}`);
      // },
      // 获取所有的editableTable实例
      addValues() {
        const form = {
          unit: this.model.unit,
          num: '',
          goalUnit: '',
          goalNum: '',
        }
        this.$refs.unitTable.push(form)
        //this.loadUnit.push(form)
        //this.list.push(form.liveId)
      },
      /**与图片上传有关的函数
       **/
      handleFileRemove(file) {
        this.model.pic = null
      },
      beforeFileUpload(file) {
        return new Promise((resolve, reject) => {
          this.$message.info('文件正在上传中...')
          return resolve(true)
        })
      },
      // 自定义上传方法
      uploadFunc(file) {
        this.confirmLoading = true
        const formData = new FormData()
        formData.append('file', file.file)
        httpAction(this.uploadUrl, formData, 'post').then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            this.model.pic = res.message
            file.onSuccess(res.data, file)
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      },
      /**图片上传函数结束
       **/

      edit (id, type) {
        this.model={};
        this.loadPrice=[];
        this.loadUnit = [];
        this.visible = true
        getMaterialsCategory().then(res=>{
          this.category = res.data;
        })
        getSupplierCode().then(res=>{
          this.supplierCode = res.data;
        })
        dropDownByCode('measurement').then(res => {
          for (let i = 0; i < this.unitTableColumns.length; i++) {
            if (this.unitTableColumns[i].key === 'goalUnit'||this.unitTableColumns[i].key === 'unit') {
              this.unitTableColumns[i].options = res.result
            }
          }
          for (let i = 0;i<this.priceTableColumns.length;i++){
            if (this.priceTableColumns[i].key === 'unit'){
              this.priceTableColumns[i].options = res.result
            }
          }
          this.units = res.result;
        })
        this.materialsId = id;
        const { form: { setFieldsValue, resetFields } } = this
        this.loadPrice = []
        this.loadUnit = []
        this.model.category = this.defaultCategory
        //console.log("默认设备类别",this.model.category)
        if (['edit', 'show'].includes(type)) {
          this.confirmLoading = true
          getObj(id).then(res => {
            //const record = res.data.records[0].baseMaterials;
            this.materialsData = res.data;
            // if(record.category === 'lineSite'){
            //   this.typeChange(record.category)
            // }
            this.confirmLoading = false
            // this.$nextTick(() => {
            //   setFieldsValue(pick(record, ['id', 'materialsCode', 'materialsName', 'category','supplierCode','unit', 'num','unitCost','minSafeStock','maxSafeStock','remarks']))
            // })
            let supplierCode = this.materialsData.baseMaterials.supplierCode;
            let supplierCodes = []
            supplierCodes = supplierCode.split(',')
            this.materialsData.baseMaterials.supplierCode = supplierCodes
            this.model = this.materialsData.baseMaterials
            this.loadPrice = this.materialsData.baseMaterialsPrices;
            //this.cachePriceData = this.loadPrice.map(item => ({ ...item }));
            this.loadUnit = this.materialsData.baseUnitConversions;
            //this.cacheUnitData = this.loadUnit.map(item => ({ ...item }));
          })

        } else {
          resetFields()
        }
      },

      // 过滤
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },

      // 暂存
      saveContract() {
        //this.model.state = 'new'
        let cases = []
        cases.push(this.$refs.editableTable)
        cases.push(this.$refs.unitTable)
        validateFormModelAndTables(this.$refs.form,this.model,cases).then(allValues => {
          let formData = this.classifyIntoFormData(allValues)
          console.log("数据",formData)
          this.handleOk(formData)
        }).catch(e => {
          console.log("出错")
        })
      },

      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let orderMain = Object.assign(this.model, allValues.formValue)
        return {
          baseMaterials:orderMain,
          price: allValues.tablesValue[0].values,
          unit: allValues.tablesValue[1].values
        }
      },
      //点击保存，执行的方法
      handleOk (formData) {
        this.form.validateFields(async (err, values) => {
          if (!err) {
            this.confirmLoading = true
            try {
              let materials = {
                id:formData.baseMaterials.id,
                materialsCode:formData.baseMaterials.materialsCode,
                materialsName:formData.baseMaterials.materialsName,
                category:formData.baseMaterials.category,
                supplierCode:formData.baseMaterials.supplierCode,
                unit:formData.baseMaterials.unit,
                num:formData.baseMaterials.num,
                unitCost:formData.baseMaterials.unitCost,
                minSafeStock:formData.baseMaterials.minSafeStock,
                maxSafeStock:formData.baseMaterials.maxSafeStock,
                pic:formData.baseMaterials.pic,
                remarks:formData.baseMaterials.remarks

              };
              //let materials = formData.baseMaterials
              let supplier = ''
              for (let i = 0;i<materials.supplierCode.length;i++){
                if (i!=0){
                  supplier = supplier+','+materials.supplierCode[i];
                }else {
                  supplier = supplier+materials.supplierCode[i];
                }
              }
              materials.supplierCode = supplier
              if (this.type === 'add') {
                await addObj(materials,formData.price,formData.unit).then(res=>{
                  if (res.code === 500||res.code === 300) {
                    this.confirmLoading = false
                    this.$message.error(res.message)
                  } else {
                    this.confirmLoading = false
                    this.$message.success('操作成功')
                    this.$emit('ok')
                    this.handleCancel()
                  }
                })
              } else if (this.type === 'edit') {
                await putObj(materials,formData.price,formData.unit).then(res=>{
                  if (res.code === 500||res.code === 300) {
                    this.confirmLoading = false
                    this.$message.error(res.message)
                  } else {
                    this.confirmLoading = false
                    this.$message.success('操作成功')
                    this.$emit('ok')
                    this.handleCancel()
                  }
                })
              }
            }catch (e){
              this.confirmLoading = false
              this.$message.error(e.msg)
            }
          }
        })
      },
      changeUnit(){
        this.loadUnit = []
        let tempUnit = [];
        this.units.forEach(item=>{
          if (item.value != this.model.unit){
            tempUnit.push(item);
          }
        })
        for (let i = 0; i < this.unitTableColumns.length; i++) {
          if (this.unitTableColumns[i].key === 'goalUnit') {
            this.unitTableColumns[i].options = tempUnit;
          }
        }
      },
      changeCategory(){
        this.$forceUpdate()
      }
    }
  }
</script>

<style scoped>

</style>